package com.tedu.cooshark.controller;

import com.tedu.cooshark.entity.Banner;
import com.tedu.cooshark.service.BannerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * 2022/3/24  14:53
 */
@RestController
@RequestMapping("/banner")
public class BannerController {
    private String dirPath = "D:/banner";
    @Autowired
    private BannerService bannerService;
    @RequestMapping("/addBanner")
    public int addBanner(@RequestBody Banner banner){
            int n = bannerService.inser(banner);
            return n;
    }
    @RequestMapping("/select")
    public List<Banner> selectBanner(){
        List<Banner> banners = bannerService.seletAll();
        return banners;
    }
    @RequestMapping("/deleteById")
    public int deleteById(@RequestBody Banner banner){
        remove(banner.getUrl());
        return bannerService.deleteById(banner);
    }
    @RequestMapping("/updateBanner")
    public int updateBanne(@RequestBody Banner banner){
        System.out.println("轮播图修改:"+banner);
        return bannerService.updateBanne(banner);
    }
    @RequestMapping("/deleteBannerByids")
    public int deleteBannerByids(@RequestBody List<Banner> banners){
        return bannerService.deleteBannerByids(banners);
    }
    @RequestMapping("/uploadBanner")
    public String upload(MultipartFile picFile) throws IOException {
        System.out.println("执行了文件上传!");
            //得到原始文件名
            String fileName=picFile.getOriginalFilename();
            //取得上传文件的后缀
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            //获取一个唯一文件id加上字符串生成心的文件名
            fileName =UUID.randomUUID()+suffix;
            //设置一个存放文件的路径
            File dirFile= new File(dirPath);
            if (!dirFile.exists()){
                dirFile.mkdirs();
            }
            //文件名加存放路径
            String filePath = dirPath+"/"+fileName;
            //将文件放入路径中
            picFile.transferTo(new File(filePath));
            return "/"+fileName;
    }
    @RequestMapping("/removeBanner")
    public void remove(String name){
        System.out.println("执行了文件删除");
        String filePath = dirPath+name;
        new File(filePath).delete();//删除文件
    }
}
